var app = angular.module('formCustSqlViewApp');
// buttons-page
app.directive('buttonsPage', function ($compile, $timeout, $injector, baseService) {

	return {
		restrict: 'E',
		templateUrl: "../../../form/formCustSql/view/buttonPageTemplate.html",
		replace: true,
		scope: {
			data: "=",
			buttonScope: "=",
			btnTypes: "=",
			list: "=",
			parent: "="
		},
		link: function (scope, elm, attrs) {

			var parent = scope.parent;
			if (!parent)
				return;
			scope.buttonScope = scope;
			scope.base = baseService;
			scope.buttonList = [];
			var ress = true
			scope.onBtnClick = function (btn, data) {
				console.log("看看有啥传递的", getCheckDataList())
				if (btn.name == "材料对比") {
					var ids = getCheckDataIds().split(",")
					console.log("btn===", ids.length, getCheckDataIds())
					if (btn.type == 2 && btn.mustSelect == 1 && ids.length <= 1) {
						jQuery.Toast.error("请选择至少两条的数据");
						return;
					}
					var arrs = []
					var arrcpmc = []
					for (var i = 0; i < getCheckDataList().length; i++) {
						arrs.push(getCheckDataList()[i].wlbm)
						arrcpmc.push(getCheckDataList()[i].cpmc)
					}
					var arrstr = arrs.join(",")
					var arrcpmcstr = arrcpmc.join(",")
					sessionStorage.setItem("arrstr", arrstr)
					sessionStorage.setItem("arrcpmcstr", arrcpmcstr)
					$.ajax({
						url: __ctx + "/sys/paramCompare/identical/" + arrstr,
						type: "get",
						dataType: "json",
						async: false,
						success: function (res) {
							// console.log("=====", res)
							if (res == "不进入") {
								ress = false
								// console.log("????")
								// return
							} else {
								ress = true
							}
						}
					})
					// console.log("=====?????", ress)
					if (ress == false) {
						console.log("????")
						jQuery.Toast.error("请选择一样的数据");
						return
					} else {
						$.ajax({
							url: __ctx + "/sys/paramCompare/compareParams/" + arrstr + "&/" + arrcpmcstr,
							type: "get",
							dataType: "json",
							async: false,
							success: function (res) {
							}
						})
					}
				}
				localStorage.setItem("btnname", btn.name)
				if (btn.type == 2 && btn.mustSelect == 1 && !getCheckDataIds()) {
					jQuery.Toast.error("请选择数据");
					return;
				}


				if (btn.warnTxt) {
					$.Dialog.confirm("温馨提示", btn.warnTxt, function () {

						triggerFn(btn, data);
					});
				} else {
					triggerFn(btn, data);
				}
			};

			var btn = scope.parent.buttonList;
			if (btn) {
				for (var i = 0; i < btn.length; i++) {
					if (scope.btnTypes.indexOf(btn[i].type) >= 0) {
						var b = angular.copy(btn[i]);
						b.onBtnClick = function (btn) {

							scope.onBtnClick(btn, scope.data, scope.list);
						}
						// button权限
						if (b.joinBtnRight) {
							b.btnRightAlias = 'customsql_button_' + parent.vo.code + "_" + b.alias;
						}
						scope.buttonList.push(b);
					}
				}
			}


			function getCheckDataList() {

				var dataList = new Array();
				//你们的BUG
				var list = scope.list;
				for (var i = 0; i < list.length; i++) {
					if (list[i].idchecked) {
						dataList.push(list[i]);
					}
				}
				return dataList;
			}
			function getCheckDataIds() {

				var list = scope.list;
				var dataList = new Array();
				for (var i = 0; i < list.length; i++) {
					if (list[i].idchecked) {
						dataList.push(list[i][parent.vo.pkName]);
					}
				}
				return dataList.join(",");
			}

			var replaceUrl = function (url, param) {

				if (!url) {
					return "";
				}
				if (!param) {
					// 没有参数则表示是全局按钮
					param = {
						id: getCheckDataIds()
					};
				}
				var hrefnew = url;
				// 替换${}
				var p1 = /\#\{(\w+)\}/g;
				try {
					var vars = hrefnew.match(p1);
					for (var i = 0; i < vars.length; i++) {
						var keyt = vars[i];
						var p2 = /\#\{(\w+)\}/g;
						var key = p2.exec(keyt);
						hrefnew = hrefnew.replace(keyt, param[key[1]]);
					}
				} catch (ex) {
				}
				// 替换#{}
				p1 = /\$\{(\w+)\}/g;
				try {
					var vars = hrefnew.match(p1);
					for (var i = 0; i < vars.length; i++) {
						var keyt = vars[i];
						var p2 = /\$\{(\w+)\}/g;
						var key = p2.exec(keyt);
						hrefnew = hrefnew.replace(keyt, param[key[1]]);
					}
				} catch (ex) {
				}
				// 替换{}
				p1 = /\{(\w+)\}/g;
				try {
					var vars = hrefnew.match(p1);
					for (var i = 0; i < vars.length; i++) {
						var keyt = vars[i];
						var p2 = /\{(\w+)\}/g;
						var key = p2.exec(keyt);
						hrefnew = hrefnew.replace(keyt, param[key[1]]);
					}
				} catch (ex) { }
				return hrefnew;
			}

			scope.excuExp = function (item, exp, type) {

				if (isStrNull(exp))
					return "";
				var data = item;// 这个变量不能删
				if (type == 1) {
					exp = "(function(){" + exp + "})()";
				}
				try {
					var returnData = eval(exp);
					if (returnData && typeof returnData == "string") {
						returnData = returnData.replaceAll("undefined", "");
					}
					return returnData;
				} catch (e) {
					return "";
				}
			}

			var psp = function (param, key) {

				var paramStr = "";
				if (param instanceof String || param instanceof Number || param instanceof Boolean) {
					paramStr += "&" + key + "=" + encodeURIComponent(param);
				} else {
					$.each(param, function (i) {

						var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
						paramStr += '&' + util.psp(this, k);
					});
				}
				return paramStr.substr(1);
			}

			var postUrl = function (url, params, btn) {
				params = params || {};
				baseService.post(url, params).then(function (data) {

					if (data.isOk) {
						jQuery.Toast.success(btn.successTxt || "操作成功~");
						parent.listScope.pageScope.$broadcast("pageDataChange", {});
					} else {
						jQuery.Toast.error(data.msg);
					}
				});
			}

			function openNewWindow(url) {
				if (url && !url.startWith("/") && !url.startWith("www") && !url.startWith("http")) {
					url = "/" + url;
				}
				if (url.startWith("/")) {
					// 获取路径
					var path = window.location.pathname.split("/")[1];
					url = "/" + path + url;
				}
				window.open(url);
			}

			function triggerFn(btn, item, list) {

				var url = replaceUrl(btn.url, item);
				var code = parent.vo.code;
				var expand = JsonUtil.ps(btn.expand) || {};
				var hrefSetting = expand.hrefSetting || {};
				var clickType = hrefSetting.openType || btn.clickType;
				var width = hrefSetting.width || "100";
				var height = hrefSetting.height || "100";
				var widthUnit = hrefSetting.widthUnit == "px" ? "" : "%";
				var heightUnit = hrefSetting.heightUnit == "px" ? "" : "%";


				switch (clickType) {
					case "0":// 直接请求
						if (!url) {
							jQuery.Toast.error("url地址为空~");
							return;
						}
						postUrl(__ctx + url, {}, btn);
						break;
					case "1":// 事件按钮
						url = __ctx + "/form/formCustSql/view/changeData_" + code + "_" + btn.alias
						if (item) {
							postUrl(url, {
								id: item[parent.vo.pkName]
							}, btn);
						} else {
							// 全局按钮
							var ids = getCheckDataIds();
							postUrl(url, {
								id: ids
							}, btn);
						}

						break;
						break;
					case "3":// 对话框
					case "4":// 对话框
						if (url && !url.startWith("/")) {
							url = "/" + url;
						}
						var conf = {
							height: height + heightUnit,
							width: width + widthUnit,
							url: url,
							title: btn.name,
							topOpen: clickType == "4"
						};
						jQuery.Dialog.open(conf);
						break;
					case "5":// 新页面
						openNewWindow(url);
						break;
					case "2":// 标签页
					default:
						// 如果是单独的页面,则直接打开新窗口
						if (!top.addTab) {
							openNewWindow(url);
							return;
						}
						if (url && url.startWith("/")) {
							url = url.substring("0", url.length);
						}
						top.addTab({
							id: btn.alias,
							name: btn.name,
							icon: btn.icon,
							url: url,
							closable: true
						})
				}
			}

		}
	};
});
// 可格式化
